package com.example.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;
@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName() + ":" + ck.getValue()));
        }
        return "获取Cookie";
    }


    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("bite") String bite) {
        return "从Cookie获取值：bite" + bite;
    }


    @RequestMapping("/setC")
    //设置session
    public String setSess(HttpServletRequest request) {
        //从cookie中获取sessionID，再根据sessionID获取session对象，如果没有获取到，就会创建一个session对象
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangSan");
        return "设置session成功";
    }


    @RequestMapping("/getSess")
    //获取session
    public String getSess(HttpServletRequest request) {
        //从cookie中获取sessionID，再根据sessionID获取session对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从session中获取name" + name;
    }


    @RequestMapping("/getSess2")
    //获取session
    public String getSess2(HttpSession session) {
        //从cookie中获取sessionID，再根据sessionID获取session对象
        String name = (String) session.getAttribute("name");
        return "从session中获取name" + name;
    }

    @RequestMapping("/getSess3")
    //获取session
    public String getSess3(@SessionAttribute("name") String name) {
        //从cookie中获取sessionID，再根据sessionID获取session对象
        return "从session中获取name" + name;
    }



}
